package com.foxitcloud.webpdf.calldll;

import java.io.File;
import java.util.Properties;

import org.apache.log4j.Logger;

public class WebReaderDllLoader {
	private static final Logger log = Logger
			.getLogger(WebReaderDllLoader.class);
	
	public static boolean isSuccessful; // For working in degraded mode? in debugging/testing, etc.

	public static void loadDlls(String nativeTempDir) {
		nativeTempDir += File.separator;
		Properties prop = System.getProperties();
		String osName = prop.getProperty("os.name");
		String osArch = prop.getProperty("os.arch");
		String pdf2imgDLLPath = "";
		String formWidgetGenDLLPath = "";
		if (osName.toLowerCase().indexOf("windows") > -1) {// the os is windows
			if (osArch.toLowerCase().equals("x86")) {
				pdf2imgDLLPath = nativeTempDir + "PDF2Image_x86.dll";
				formWidgetGenDLLPath = nativeTempDir + "FormWidgetGen_x86.dll";
			} else {
				pdf2imgDLLPath = nativeTempDir + "PDF2Image_x64.dll";
				formWidgetGenDLLPath = nativeTempDir + "FormWidgetGen_x64.dll";
			}
		} else {// the os is linux
			if (osArch.toLowerCase().equals("x86")) {
				//log.warn("Current version not support for Linux x86");
				//System.exit(1);
				pdf2imgDLLPath = nativeTempDir + "libPDF2Image.so";
				formWidgetGenDLLPath = nativeTempDir + "libFormWidgetGen.so";
			} else {
				pdf2imgDLLPath = nativeTempDir + "libPDF2Image.so";
				formWidgetGenDLLPath = nativeTempDir + "libFormWidgetGen.so";
			}
		}
		
		isSuccessful = true; // Assume loading will succeed.
		
		try {
			System.load(pdf2imgDLLPath);
		} catch (UnsatisfiedLinkError e) {
			log.error("Load native library PDF2Image failed, path:"
					+ pdf2imgDLLPath + ". System now operating in degraded mode", e);
			// System.exit(1);
			isSuccessful = false;
		}

		try {
			System.load(formWidgetGenDLLPath);
		} catch (UnsatisfiedLinkError e) {
			log.error("Load native library FormWidgetGen failed, path:"
					+ formWidgetGenDLLPath + ". System now operating in degraded mode", e);
			// System.exit(1); // Commented out by Steven on 2/2/2015, to support "degraded mode", so that we can run/debug easily without the SO files
			isSuccessful = false;
		}
	}
}
